import React from 'react'
import { connect } from "react-redux"; // 2、connect：连接器
import store from '../store';
import { changeInputAction, addItemAction, deleteItemAction } from "../store/actionCreatores";

// 修改为无状态组件
const TodoList = (props) => {
    const { inputValue, list, inputChange, handleClickBtn, handleDelData } = props;
    return (
        <div>
            <div>
                <input value={inputValue} onChange={inputChange} type="text" />
                <button type="button" onClick={handleClickBtn}>提交</button>
            </div>
            <div>
                <ul>
                    {
                        list.map((item, index) => {
                            return (
                                <li key={index} onClick={() => handleDelData(index)}>{item}</li>
                            )
                        })
                    }
                </ul>
            </div>
        </div>
    )
}

// 3、映射值
const stateToProps = (state) => {
    return {
        inputValue: state.inputValue,
        list: state.list
    }
}

const dispatchToProps = (dispatch) => {
    return {
        inputChange(e) {
            const action = changeInputAction(e.target.value);
            dispatch(action);
        },
        // 提交
        handleClickBtn() {
            const { inputValue } = store.getState();
            if (!inputValue) return;
            const action = addItemAction();
            dispatch(action);
        },
        // 删除
        handleDelData(index) {
            const action = deleteItemAction(index);
            dispatch(action);
        }
    }
}

export default connect(stateToProps, dispatchToProps)(TodoList);